# ///////////////////////////////////////////////////////////////
#
# BY: WANDERSON M.PIMENTA
# PROJECT MADE WITH: Qt Designer and PySide6
# V: 1.0.0
#
# This project can be used freely for all uses, as long as they maintain the
# respective credits only in the Python scripts, any information in the visual
# interface (GUI) can be modified without any implication.
#
# There are limitations on Qt licenses if you want to use your products
# commercially, I recommend reading them on the official website:
# https://doc.qt.io/qtforpython/licenses.html
#
# ///////////////////////////////////////////////////////////////

# MAIN FILE
# ///////////////////////////////////////////////////////////////
import socket
from fractions import Fraction
from main import *
from modules.ui_set_alarm import Ui_Dialog_Set_Alarm
from modules.ui_group import Ui_Dialog_Group
from modules.ui_login import Ui_Dialog_Login

from modules.ui_system_more_info import Ui_Form_System_More_info
from modules.ui_system_control import Ui_Form_System_Control
import requests
import json
import time
# import ui_login
# GLOBALS
# ///////////////////////////////////////////////////////////////
GLOBAL_STATE = False
GLOBAL_TITLE_BAR = True

class UIFunctions(MainWindow):
    # MAXIMIZE/RESTORE
    # ///////////////////////////////////////////////////////////////
    def maximize_restore(self):
        global GLOBAL_STATE
        status = GLOBAL_STATE
        if status == False:
            # return
            # self.showMaximized()
            self.resize(1920,1020)
            GLOBAL_STATE = True
            self.ui.appMargins.setContentsMargins(0, 0, 0, 0)
            self.ui.maximizeRestoreAppBtn.setToolTip("Restore")
            self.ui.maximizeRestoreAppBtn.setIcon(QIcon(u":/icons/images/icons/icon_restore.png"))
            self.ui.frame_size_grip.hide()
            self.left_grip.hide()
            self.right_grip.hide()
            self.top_grip.hide()
            self.bottom_grip.hide()
        else:
            GLOBAL_STATE = False
            self.showNormal()
            self.resize(self.width()+1, self.height()+1)
            self.ui.appMargins.setContentsMargins(10, 10, 10, 10)
            self.ui.maximizeRestoreAppBtn.setToolTip("Maximize")
            self.ui.maximizeRestoreAppBtn.setIcon(QIcon(u":/icons/images/icons/icon_maximize.png"))
            self.ui.frame_size_grip.show()
            self.left_grip.show()
            self.right_grip.show()
            self.top_grip.show()
            self.bottom_grip.show()

    # RETURN STATUS
    # ///////////////////////////////////////////////////////////////
    def returStatus(self):
        return GLOBAL_STATE

    # SET STATUS
    # ///////////////////////////////////////////////////////////////
    def setStatus(self, status):
        global GLOBAL_STATE
        GLOBAL_STATE = status

    # TOGGLE MENU
    # ///////////////////////////////////////////////////////////////
    def toggleMenu(self, enable):
        if enable:
            # GET WIDTH
            width = self.ui.leftMenuBg.width()
            maxExtend = Settings.MENU_WIDTH
            standard = 60

            # SET MAX WIDTH
            if width == 60:
                widthExtended = maxExtend
            else:
                widthExtended = standard

            # ANIMATION
            self.animation = QPropertyAnimation(self.ui.leftMenuBg, b"minimumWidth")
            self.animation.setDuration(Settings.TIME_ANIMATION)
            self.animation.setStartValue(width)
            self.animation.setEndValue(widthExtended)
            self.animation.setEasingCurve(QEasingCurve.InOutQuart)
            self.animation.start()

    # TOGGLE LEFT BOX
    # ///////////////////////////////////////////////////////////////
    def toggleLeftBox(self, enable):
        if enable:
            # GET WIDTH
            width = self.ui.extraLeftBox.width()
            widthRightBox = self.ui.extraRightBox.width()
            maxExtend = Settings.LEFT_BOX_WIDTH
            color = Settings.BTN_LEFT_BOX_COLOR
            standard = 0

            # GET BTN STYLE
            style = self.ui.toggleLeftBox.styleSheet()

            # SET MAX WIDTH
            if width == 0:
                widthExtended = maxExtend
                # SELECT BTN
                self.ui.toggleLeftBox.setStyleSheet(style + color)
                if widthRightBox != 0:
                    style = self.ui.settingsTopBtn.styleSheet()
                    self.ui.settingsTopBtn.setStyleSheet(style.replace(Settings.BTN_RIGHT_BOX_COLOR, ''))
            else:
                widthExtended = standard
                # RESET BTN
                self.ui.toggleLeftBox.setStyleSheet(style.replace(color, ''))
                
        UIFunctions.start_box_animation(self, width, widthRightBox, "left")

    # TOGGLE RIGHT BOX
    # ///////////////////////////////////////////////////////////////
    def toggleRightBox(self, enable):
        if enable:
            # GET WIDTH
            width = self.ui.extraRightBox.width()
            widthLeftBox = self.ui.extraLeftBox.width()
            maxExtend = Settings.RIGHT_BOX_WIDTH
            color = Settings.BTN_RIGHT_BOX_COLOR
            standard = 0

            # GET BTN STYLE
            style = self.ui.settingsTopBtn.styleSheet()

            # SET MAX WIDTH
            if width == 0:
                widthExtended = maxExtend
                # SELECT BTN
                self.ui.settingsTopBtn.setStyleSheet(style + color)
                if widthLeftBox != 0:
                    style = self.ui.toggleLeftBox.styleSheet()
                    self.ui.toggleLeftBox.setStyleSheet(style.replace(Settings.BTN_LEFT_BOX_COLOR, ''))
            else:
                widthExtended = standard
                # RESET BTN
                self.ui.settingsTopBtn.setStyleSheet(style.replace(color, ''))

            UIFunctions.start_box_animation(self, widthLeftBox, width, "right")

    def start_box_animation(self, left_box_width, right_box_width, direction):
        right_width = 0
        left_width = 0 

        # Check values
        if left_box_width == 0 and direction == "left":
            left_width = 240
        else:
            left_width = 0
        # Check values
        if right_box_width == 0 and direction == "right":
            right_width = 240
        else:
            right_width = 0       

        # ANIMATION LEFT BOX        
        self.left_box = QPropertyAnimation(self.ui.extraLeftBox, b"minimumWidth")
        self.left_box.setDuration(Settings.TIME_ANIMATION)
        self.left_box.setStartValue(left_box_width)
        self.left_box.setEndValue(left_width)
        self.left_box.setEasingCurve(QEasingCurve.InOutQuart)

        # ANIMATION RIGHT BOX        
        self.right_box = QPropertyAnimation(self.ui.extraRightBox, b"minimumWidth")
        self.right_box.setDuration(Settings.TIME_ANIMATION)
        self.right_box.setStartValue(right_box_width)
        self.right_box.setEndValue(right_width)
        self.right_box.setEasingCurve(QEasingCurve.InOutQuart)

        # GROUP ANIMATION
        self.group = QParallelAnimationGroup()
        self.group.addAnimation(self.left_box)
        self.group.addAnimation(self.right_box)
        self.group.start()

    # SELECT/DESELECT MENU
    # ///////////////////////////////////////////////////////////////
    # SELECT
    def selectMenu(getStyle):
        select = getStyle + Settings.MENU_SELECTED_STYLESHEET
        return select

    # DESELECT
    def deselectMenu(getStyle):
        deselect = getStyle.replace(Settings.MENU_SELECTED_STYLESHEET, "")
        return deselect

    # START SELECTION
    def selectStandardMenu(self, widget):
        for w in self.ui.topMenu.findChildren(QPushButton):
            if w.objectName() == widget:
                w.setStyleSheet(UIFunctions.selectMenu(w.styleSheet()))

    # RESET SELECTION
    def resetStyle(self, widget):
        for w in self.ui.topMenu.findChildren(QPushButton):
            if w.objectName() != widget:
                w.setStyleSheet(UIFunctions.deselectMenu(w.styleSheet()))

    # IMPORT THEMES FILES QSS/CSS
    # ///////////////////////////////////////////////////////////////
    def theme(self, file, useCustomTheme):
        if useCustomTheme:
            str = open(file, 'r').read()
            self.ui.styleSheet.setStyleSheet(str)

    # START - GUI DEFINITIONS
    # ///////////////////////////////////////////////////////////////
    def uiDefinitions(self):
        def dobleClickMaximizeRestore(event):
            # IF DOUBLE CLICK CHANGE STATUS
            if event.type() == QEvent.MouseButtonDblClick:
                QTimer.singleShot(250, lambda: UIFunctions.maximize_restore(self))
        self.ui.titleRightInfo.mouseDoubleClickEvent = dobleClickMaximizeRestore

        if Settings.ENABLE_CUSTOM_TITLE_BAR:
            #STANDARD TITLE BAR
            self.setWindowFlags(Qt.FramelessWindowHint)
            self.setAttribute(Qt.WA_TranslucentBackground)

            # MOVE WINDOW / MAXIMIZE / RESTORE
            def moveWindow(event):
                # IF MAXIMIZED CHANGE TO NORMAL
                if UIFunctions.returStatus(self):
                    UIFunctions.maximize_restore(self)
                # MOVE WINDOW
                if event.buttons() == Qt.LeftButton:
                    self.move(self.pos() + event.globalPos() - self.dragPos)
                    self.dragPos = event.globalPos()
                    event.accept()
            self.ui.titleRightInfo.mouseMoveEvent = moveWindow

            # CUSTOM GRIPS
            self.left_grip = CustomGrip(self, Qt.LeftEdge, True)
            self.right_grip = CustomGrip(self, Qt.RightEdge, True)
            self.top_grip = CustomGrip(self, Qt.TopEdge, True)
            self.bottom_grip = CustomGrip(self, Qt.BottomEdge, True)

        else:
            self.ui.appMargins.setContentsMargins(0, 0, 0, 0)
            self.ui.minimizeAppBtn.hide()
            self.ui.maximizeRestoreAppBtn.hide()
            self.ui.closeAppBtn.hide()
            self.ui.frame_size_grip.hide()

        # DROP SHADOW
        self.shadow = QGraphicsDropShadowEffect(self)
        self.shadow.setBlurRadius(17)
        self.shadow.setXOffset(0)
        self.shadow.setYOffset(0)
        self.shadow.setColor(QColor(0, 0, 0, 150))
        self.ui.bgApp.setGraphicsEffect(self.shadow)

        # RESIZE WINDOW
        self.sizegrip = QSizeGrip(self.ui.frame_size_grip)
        self.sizegrip.setStyleSheet("width: 20px; height: 20px; margin 0px; padding: 0px;")

        # MINIMIZE
        self.ui.minimizeAppBtn.clicked.connect(lambda: self.showMinimized())

        # MAXIMIZE/RESTORE
        self.ui.maximizeRestoreAppBtn.clicked.connect(lambda: UIFunctions.maximize_restore(self))

        # CLOSE APPLICATION
        self.ui.closeAppBtn.clicked.connect(lambda: self.close())

    def resize_grips(self):
        if Settings.ENABLE_CUSTOM_TITLE_BAR:
            self.left_grip.setGeometry(0, 10, 10, self.height())
            self.right_grip.setGeometry(self.width() - 10, 10, 10, self.height())
            self.top_grip.setGeometry(0, 0, self.width(), 10)
            self.bottom_grip.setGeometry(0, self.height() - 10, self.width(), 10)

    # ///////////////////////////////////////////////////////////////
    # END - GUI DEFINITIONS
class MyLoginDialog(QDialog):
    """登录窗口类"""
    signal_login = Signal(dict)
    def __init__(self):
        super().__init__()
        self.ui = Ui_Dialog_Login()
        self.ui.setupUi(self)
        self.ui.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setText('登录')
        self.ui.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setText('关闭')
        self.ui.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setMinimumWidth(100)
        self.ui.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setMaximumWidth(100)
        self.ui.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setMinimumWidth(100)
        self.ui.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setMaximumWidth(100)
        self.setAttribute(Qt.WA_TranslucentBackground) 
        self.ui.LineEdit_3.setPlaceholderText('修改后请直接点击登录')
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint)
        self.ui.pushButton.clicked.connect(self.enablele)
        self.t = QTimer() 
        self.userid()
        self.thame_init()
    def thame_init(self):
        stylesheet = open(file='themes\\dialog.qss',mode='r',encoding='utf-8').read()
        self.setStyleSheet(stylesheet)
    def enablele(self):
        if not self.ui.LineEdit_3.isEnabled():
            self.ui.LineEdit_3.setEnabled(True)
            self.ui.LineEdit_3.setPlaceholderText('开启密码修改')
        else:
            self.ui.LineEdit_3.setEnabled(False)
            self.ui.LineEdit_3.setText('')
            self.ui.LineEdit_3.setPlaceholderText('关闭密码修改')
    def accept(self):
        self.ui.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setEnabled(False)
        self.ui.label.setText('请稍候！')
        
        self.login()
    def userid(self):
        try:
            with open('userid.json',mode='r') as f:
                userid = json.load(f)
                if userid.get('flag'):
                    self.ui.LineEdit.setText(userid.get('username'))
                    self.ui.LineEdit_2.setText(userid.get('password'))
                    self.ui.checkBox.setCheckState(Qt.CheckState.Checked)
        except Exception as e:
            print(e) 
    def login(self):
        username = self.ui.LineEdit.text()
        password = self.ui.LineEdit_2.text()
        newpassword = self.ui.LineEdit_3.text()
        data = {
                "username": username,
                "password": password,
                "uuid":"",
                'group':{},
                'newpassword':newpassword
                }
        # print(data)
        if self.ui.checkBox.checkState()==Qt.CheckState.Checked:
            with open('userid.json',mode='w') as f:
                if len(newpassword):
                    password = newpassword
                userid = {
                "username": username,
                "password": password,
                "flag":1
                }
                json.dump(userid,f)
        else:
            with open('userid.json',mode='w') as f:
                userid = {
                "username": "username",
                "password": 'password',
                "flag":0
                }
                json.dump(userid,f)
            # pass
            # 打开pass文件保存
            # 
        try :
            res = requests.post(url=Settings.APPURL+'login',json=data,timeout=5).json()
            if (res.get('status').startswith('修')or(res.get('status').startswith('登'))):
                self.signal_login.emit(res)
                self.setlable(text=res.get('status'))
                QTimer.singleShot(2000,self.close)
                # return super().accept()
            else:
                self.setlable(text=f'{res.get("status")}')
                self.ui.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setEnabled(True)
        except requests.exceptions.RequestException as e:
            self.ui.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setEnabled(True)
            self.setlable(text='登录超时，请检查网络！！') 
    def setlable(self,text= ''):
        self.ui.label.setText(f'{text}')
        self.t.singleShot(5000,self.ui.label.clear)


class MyUserGroupDialog(QDialog):
    """用户分组设置界面"""
    signal_usergroup = Signal(dict)
    def __init__(self,user_init:dict):
        super().__init__()
        self.user_init = user_init
        self.ui = Ui_Dialog_Group()
        self.ui.setupUi(self)
        self.t = QTimer()
        self.group = user_init.get('group')

        self.init_widgets()
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint)
        self.ui.buttonBox.button(QDialogButtonBox.StandardButton.Save).setText('保存上传') 
        self.ui.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setText('退出修改') 
        self.ui.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).clicked.connect(self.close)
        self.setWindowTitle('分组设置')
        self.thame_init()
    def thame_init(self):
        stylesheet = open(file='themes\\dialog.qss',mode='r',encoding='utf-8').read()
        self.setStyleSheet(stylesheet)
    def accept(self):
        self.signal_usergroup.emit(self.user_init)
        return super().accept()
    def close(self):
        self.signal_usergroup.emit(self.user_init)
        return super().close()
    def init_widgets(self):
        # 获得用户列表，更新选择框

        self.ui.comboBox.addItems(list(self.group.keys()))
        
        # 根据用户列表的第一个选项更新表格，表格自动获得所有所有站点
        group1 = self.ui.comboBox.currentText()
        self.init_table(self.get_group(),group1)

        self.ui.tableWidget.itemClicked.connect(self.set_checked)
        # 绑定控件函数
        self.ui.btn_new.clicked.connect(self.set_enable)

        self.ui.btn_save.clicked.connect(self.save_group)

        self.ui.comboBox.currentTextChanged.connect(lambda x : self.init_table([],x))

        # self.ui.pushButton_3.clicked.connect(lambda : print(self.user_init))
        self.ui.tableWidget.setSortingEnabled(True)

        self.ui.btn_clear.clicked.connect(self.clearchecked)

        self.ui.cb_source.currentTextChanged.connect(self.source_cb_change)

        self.ui.cb_company.currentTextChanged.connect(self.company_cb_change)

        self.ui.lineEdit_2.textChanged.connect(self.findabc)
        self.ui.btn_del.clicked.connect(self.del_group_msg)
        self.ui.btn_save.setText('保存新建/修改')
        self.ui.btn_modify.clicked.connect(self.modify_group)
        self.ui.btn_modify.hide()
    def modify_group(self):
        print(self.user_init)
        print(self.group)
    def del_group_msg(self):
        del_group_name = self.ui.lineEdit.text().strip()
        reply = QMessageBox()
        reply.setWindowTitle('确认删除')
        reply.setText(f'确认删除分组：{del_group_name}')
        btn_yes = reply.addButton("确定", QMessageBox.AcceptRole)
        btn_cancel = reply.addButton("取消", QMessageBox.RejectRole)
        btn_yes.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        btn_cancel.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        btn_yes.clicked.connect(lambda:self.del_group(del_group_name))
        res = reply.exec()
    def del_group(self,del_group_name):
        
        self.group.pop(del_group_name)
       
        self.user_init['group'] = self.group
        self.ui.comboBox.clear()
        self.ui.comboBox.addItems(list(self.group.keys()))
        data = {
            'uuid':self.user_init.get('uuid'),
            'new_group':self.group
        }
        requests.post(url=Settings.APPURL+'/delgroup',json=data)
        self.ui.lineEdit.setText('')
    def findabc(self,text:str):
        text = text.upper()
        row = self.ui.tableWidget.rowCount()
        for i in range(row):
            self.ui.tableWidget.showRow(i)
        for i in range(row):
            abc = self.ui.tableWidget.item(i,3).text()
            if abc.startswith(text):
                continue
            else:
                self.ui.tableWidget.hideRow(i)
        
    # self.ui.tableWidget.finn
    def company_cb_change(self,text):
        self.filter_sou_com()        
    def source_cb_change(self,text):
        self.filter_sou_com()
    def filter_sou_com(self):
        source = self.ui.cb_source.currentText()
        company = self.ui.cb_company.currentText()
        row = self.ui.tableWidget.rowCount()
        
        for i in range(row):
            item_source = self.ui.tableWidget.item(i,4).text()
            item_company = self.ui.tableWidget.item(i,5).text()
                
            self.ui.tableWidget.showRow(i)
            if (source == item_source or source=='全部热源') and (item_company == company or company =='全部分公司'):
                continue
            else:
                self.ui.tableWidget.hideRow(i)
    def clearchecked(self):
        col = self.ui.tableWidget.columnCount()
        row = self.ui.tableWidget.rowCount()
        for i in range(row):
            item = self.ui.tableWidget.item(i,col-1)
            item.setCheckState(Qt.CheckState.Unchecked)
            item.setText("")
        
    def filltableview(self):

        self.ui.tableWidget.setItem()
    def get_group(self):
        res = requests.get(url=Settings.APPURL+'all_group').json()
        return res
    def init_table(self,data:list,usergroup:str):
        self.ui.lineEdit.setText(usergroup)
        if len(data):
            self.tableCol = len(data[0])
            self.tableRow = len(data)
            self.ui.tableWidget.setColumnCount(self.tableCol +1)
            self.ui.tableWidget.setRowCount(self.tableRow)
            
            for i,j in enumerate(data):
                for x,y in enumerate(j):
                    item = QTableWidgetItem(str(y))
                    self.ui.tableWidget.setItem(i,x,item)
                    if x == len(j) - 1:
                        it = QTableWidgetItem()
                        it.setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled)
                        it.setCheckState(Qt.Unchecked)
                        self.ui.tableWidget.setItem(i,x+1,it)
            self.ui.tableWidget.setHorizontalHeaderLabels(['系统编号','net_id','source_id','首字母','所属热源','所属分公司','站点名称','系统名称','是否选择'])
        if not usergroup :
            return
        usergroup_list = json.loads(self.get_user_group(self.group.get(usergroup)))

        for i in range(self.ui.tableWidget.rowCount()):
            table_item = self.ui.tableWidget.item(i,self.ui.tableWidget.columnCount()-1)
            table_item.setCheckState(Qt.CheckState.Unchecked)
            table_item.setText('')
            self.ui.tableWidget.item(i,self.ui.tableWidget.columnCount()-1).setText('')

        for i in usergroup_list:
            res = self.ui.tableWidget.findItems(i,Qt.MatchFlag.MatchContains)
            table_item = self.ui.tableWidget.item(res[0].row(),self.ui.tableWidget.columnCount()-1)
            table_item.setCheckState(Qt.CheckState.Checked)
            table_item.setText('已选择')
        for i in range(4):
            # continue
            self.ui.tableWidget.hideColumn(i)
                

    def save_group(self):
        # 保存当前选中的站点
        self.l = []
        name = self.ui.lineEdit.text()
        for i in range(self.tableRow):
            if(self.ui.tableWidget.item(i,self.tableCol).checkState()==Qt.CheckState.Checked):
                self.l.append(self.ui.tableWidget.item(i,0).text())
        # 更新分组字典
        group_name = self.ui.lineEdit.text()
        data = {
            'uuid':self.user_init.get('uuid'),
            'name':group_name,
            'index':json.dumps(self.l)
        }
        # print(data)
        res = requests.post(url=Settings.APPURL+'updategroup',json=data)
        usregroup = res.json()
        self.ui.comboBox.clear()
        self.ui.comboBox.addItems(list(usregroup.keys()))
        self.user_init['group'] = usregroup
        self.group = usregroup
        # 获得返回的列表，更新主程序列表和当前窗口列表
        reply = QMessageBox(
            
            text='保存成功！'
        )
        reply.setWindowTitle('通知')
        reply.exec()

    def set_checked(self,item:QTableWidgetItem):
        if item.column() != 8:
            return
        if item.checkState() == Qt.CheckState.Unchecked:
            item.setText('已选择')
            item.setCheckState(Qt.CheckState.Checked)
        else:
            item.setText('')    
            item.setCheckState(Qt.CheckState.Unchecked)
    def set_enable(self):
        if self.ui.lineEdit.isEnabled():
            self.ui.lineEdit.setEnabled(False)
            self.ui.lineEdit.setPlaceholderText('分组名称')
        else :
            self.ui.lineEdit.setEnabled(True)
            self.ui.lineEdit.setText('')
            self.ui.lineEdit.setPlaceholderText('请输入新分组名称！')
        
    def get_user_group(self,id:int):
        # print('groupid',id)
        res = requests.get(url=Settings.APPURL+f'getusergroup/{id}').json()
        return res
class MySetAlarmDialog(QDialog):
    alarm_signal = Signal(dict)
    def __init__(self,sysid:str,user_init:dict):
        super().__init__()
        self.ui = Ui_Dialog_Set_Alarm()
        self.ui.setupUi(self)
        self.sysid = sysid
        self.sysnum = sysid[-1:]
        self.user_init = user_init
        # self.ui.pushButton.clicked.connect(self.update_alarm)
        self.ui.pushButton.hide()
        self.get_sys_data()
        self.ui.tableWidget.itemClicked.connect(self.checked)
        self.t = QTimer()
        self.setWindowTitle('报警设置')
        # self.ui.lineEdit.textChanged.connect(self.locate_var)
        self.ui.lineEdit.textChanged.connect(self.findabc)
        self.ui.label_2.setText('请同时输入参与报警变量的最小值和最大值，低于或超出该范围后将自动发出报警\n输入数值必须是小数，例如1.2，0.25，20.0')
        self.thame_init()
        self.ui.tableWidget.resizeColumnsToContents()
        self.ui.tableWidget.setColumnWidth(0,2)

    def thame_init(self):
        stylesheet = open(file='themes\\dialog.qss',mode='r',encoding='utf-8').read()
        self.setStyleSheet(stylesheet)
    def get_sys_data(self):
        self.ui.buttonBox.button(QDialogButtonBox.StandardButton.Ok).setText('完成保存')
        self.ui.buttonBox.button(QDialogButtonBox.StandardButton.Cancel).setText('取消退出')
        self.ui.label_2.setText('')
        url = Settings.APPURL+'getone/'+self.sysid
        res = requests.get(url=url).json()
        var_name = res.get('var_name')
        # 1获得站点数据
        l_old = list(var_name.keys())
        self.ui.tableWidget.setRowCount(len(l_old))
        l = list(map(lambda x:x.replace('.1.',f'.{self.sysnum}.'),l_old))
        l = list(map(self.get_var_list,l))
        res_data = res.get("data")
        # print(l)
        # 2填充表格
        for i,j in enumerate(l):

            # var = self.sysid[:-1]+j   
            item0 = QTableWidgetItem(j)
            item0.setFlags(item0.flags() & ~Qt.ItemFlag.ItemIsEditable)
            self.ui.tableWidget.setItem(i,0,item0)

            v_chinese = var_name.get(l_old[i])
            item1 = QTableWidgetItem(v_chinese)
            item1.setFlags(item1.flags() & ~Qt.ItemFlag.ItemIsEditable)
            self.ui.tableWidget.setItem(i,1,item1)

            data = res_data.get(j)
            if type(data) ==float:
                data = round(data,3)
            item2 = QTableWidgetItem(str(data))
            item2.setFlags(item2.flags() & ~Qt.ItemFlag.ItemIsEditable)
            self.ui.tableWidget.setItem(i,2,item2)

            iteml = QTableWidgetItem()
            itemh = QTableWidgetItem()
            iteml.setFlags(iteml.flags() & ~Qt.ItemFlag.ItemIsEditable)
            itemh.setFlags(itemh.flags() & ~Qt.ItemFlag.ItemIsEditable)
            self.ui.tableWidget.setItem(i,3,iteml)
            self.ui.tableWidget.setItem(i,4,itemh)

            item5 = QTableWidgetItem()
            item5.setFlags(item5.flags() & ~Qt.ItemFlag.ItemIsEditable)
            item5.setCheckState(Qt.CheckState.Unchecked)

            self.ui.tableWidget.setItem(i,5,item5)
        # 3是否设置过报警
        # 获得用户的报警列表，查询哪些参数是报警参数，从而设置哪些为报警参量
        row = self.ui.tableWidget.rowCount()
        col = self.ui.tableWidget.columnCount()
        # 获得默认报警列表///////////////////////////////////////////
        self.alarm_group = self.user_init.get('alarm_group') if self.user_init.get('alarm_group') else dict()
# ////////////////////////////////////////
        
        alarm_keys_set = set() if self.alarm_group is None else set(self.alarm_group.keys()) 
        self.var_set = set(l)
        self.var_set = self.var_set & alarm_keys_set
        if not len(self.var_set):
            return
        for i in self.var_set:
            for j in range(row):
                if self.ui.tableWidget.item(j,0).text()==i:
                    system_alarm_dict = self.alarm_group.get(i)
                    l = self.ui.tableWidget.item(j,3)
                    h = self.ui.tableWidget.item(j,4)
                    l.setText(str(system_alarm_dict.get('l')))
                    h.setText(str(system_alarm_dict.get('h')))
                    l.setFlags(l.flags() | Qt.ItemFlag.ItemIsEditable)
                    h.setFlags(l.flags() | Qt.ItemFlag.ItemIsEditable)
                    self.ui.tableWidget.item(j,5).setText(str(system_alarm_dict.get('enable')))
                    self.ui.tableWidget.item(j,5).setCheckState(Qt.CheckState.Checked)
                        


        self.ui.tableWidget.hideColumn(0)

    def get_var_list(self,s:str):
        return self.sysid[:-1]+s

    def checked(self,item:QTableWidgetItem):
        if item.column() != 5:
            return
        if item.row()<=11:
            item.setCheckState(Qt.CheckState.Unchecked)
            self.label_text(f'第{item.row()+1}行静态信息无法报警！')
            return
        l = self.ui.tableWidget.item(item.row(),3)
        h = self.ui.tableWidget.item(item.row(),4)
        if item.checkState() == Qt.CheckState.Unchecked:
            item.setCheckState(Qt.CheckState.Checked)
            item.setText('开启')
            # print(l.flags())
            l.setFlags(l.flags() | Qt.ItemFlag.ItemIsEditable)
            h.setFlags(h.flags() | Qt.ItemFlag.ItemIsEditable)
        else:
            item.setCheckState(Qt.CheckState.Unchecked)
            item.setText('')
            # print(l.flags())
            l.setFlags(l.flags() & ~Qt.ItemFlag.ItemIsEditable)
            h.setFlags(h.flags() & ~Qt.ItemFlag.ItemIsEditable)
            l.setText('')
            h.setText('')
        # print(*args)
    def keyPressEvent(self, arg__1:QKeyEvent):
        if arg__1.key()==16777220:
            return
        return super().keyPressEvent(arg__1)
    def accept(self):
        
        if self.update_alarm():
            self.close()
            # return super().accept()
    # @classmethod
    def is_rational(self,s):  
        s = s.strip()  
        if not s:  
            return False  
        try:  
            # 尝试转换为Fraction  
            Fraction(s)  
            return True  
        except (ValueError, ZeroDivisionError, TypeError):  
            return False
    def update_alarm(self):
        # print(self.user_init)
        col = self.ui.tableWidget.colorCount()
        row = self.ui.tableWidget.rowCount()
        alarm_group_inner = {}
        for i in range(row):
        # 获得所有启用的变量
            item = self.ui.tableWidget.item(i,5)
            if item.checkState()==Qt.CheckState.Checked:
                var_name = self.ui.tableWidget.item(i,0).text()
        # 判断变量上下限是否合理
                l = self.ui.tableWidget.item(i,3)
                l_text = l.text()
                l_text = l_text.strip()
                # print(l_text)
                if  l_text.isdecimal() or not l_text.__len__():
                    
                    self.label_text(f'{i+1}行最小值参数设置有误,必须为小数（xx.0 xx.1）！')
                    
                    return
                h = self.ui.tableWidget.item(i,4)
                h_text = h.text()
                h_text = h_text.strip()
                if h_text.isdecimal()  or not h_text.__len__():
                    self.label_text(f'{i+1}行最大值参数设置有误！,必须为小数（xx.0 xx.1）！')
                    return
                if float(l_text)>=float(h_text):
                    self.label_text(f'{item.row()+1}行低高限设置有问题！')
                    return
                station = self.ui.tableWidget.item(8,2).text()
                system = self.ui.tableWidget.item(9,2).text()
                alarm_point_name = self.ui.tableWidget.item(i,1).text()
                alarm_group_inner[var_name]=dict([['l',l_text],['h',h_text],['enable','开启'],['station',station],['system',system],['alarm_point_name',alarm_point_name ]])
        for i in self.var_set:
            del self.alarm_group[i]
        self.alarm_group.update(alarm_group_inner)
        # print(self.alarm_group)
        data = {
            'useruuid':self.user_init.get('uuid'),
            'alarm_group':self.alarm_group

        }
        
        res = requests.post(url=Settings.APPURL+'updatealarmgroup',json=data).json()
        
        # print(res.json())
        if res.get('status')==200:
            self.alarm_signal.emit(self.alarm_group)
        return 1
        # 删除原有的关于这个系统的报警参数
        # 获得原本有关于本系统的报警变量
    def findabc(self,text:str):
        text = text.upper()
        row = self.ui.tableWidget.rowCount()
        for i in range(row):
            self.ui.tableWidget.showRow(i)
        for i in range(row):
            abc = self.ui.tableWidget.item(i,1).text()
            if abc.startswith(text):
                continue
            else:
                self.ui.tableWidget.hideRow(i)
    def label_text(self,text:str):
        self.ui.label_2.setText(text)
        self.t.singleShot(3000,self.ui.label_2.clear)
    def locate_var(self):
        text = self.ui.lineEdit.text()
        finditems = self.ui.tableWidget.findItems(text,Qt.MatchFlag.MatchContains)
        try:
            finditems[0].setSelected(True)
            self.ui.tableWidget.scrollToItem(finditems[0])
        except Exception as e:
            print(e)
            # pass

        # 增加新的报警配置
        # 保存并上传
class MySystemMoreInfo(QDialog):
    """供热系统的全部信息"""
    def __init__(self,sysid:str):
        super().__init__()
        self.ui = Ui_Form_System_More_info()
        self.ui.setupUi(self)
        self.url = Settings.APPURL
        # print(sysid)
        self.sysid = sysid
        self.dict_info=self.dict_init()
        self.fill_tv()
        self.ui.btn_resize.clicked.connect(self.tv_resize)
        self.setWindowTitle('全部数据')
        self.thame_init()
    def thame_init(self):
        stylesheet = open(file='themes\\dialog.qss',mode='r',encoding='utf-8').read()
        self.setStyleSheet(stylesheet)
    def tv_resize(self):
        for i in [self.ui.tv_system_data,self.ui.tv_system_data_1,self.ui.tv_system_data_2,self.ui.tv_system_data_3]:
            i.resizeColumnsToContents()
            i.setColumnWidth(0,1)
    def fill_tv(self):
        res = requests.get(url=self.url+f'getone/{self.sysid}').json()
        data:dict = res.get('data')
        data_list = list(data.items())
        tv_model = QStandardItemModel()
        for i,j in data_list:
            key = QStandardItem(str(i))
            value = QStandardItem(str(j))
            tv_model.appendRow([key,value])
        self.ui.tv_system_data.setModel(tv_model)
        # print(res)
        vd0= 'ValueDesc.0'
        vd1= 'ValueDesc.1'
        vd2= 'ValueDesc.2'
        vd3= 'ValueDesc.3'
        vpd0 = 'ValueParaDesc.0'
        vpd1 = 'ValueParaDesc.1'
        vpd2 = 'ValueParaDesc.2'
        vpd3 = 'ValueParaDesc.3'
        si = 'StaticInfo'
        # ValueParaDesc.1
        # StaticInfo
        si_model=QStandardItemModel()
        s1_model=QStandardItemModel()
        s2_model=QStandardItemModel()
        s3_model=QStandardItemModel()
        header_label = ['代号','变量名称','变量值']
        si_list = []
        s1_list = []
        s2_list = []
        s3_list = []
        for i in data_list:
            if (vd0 in i[0]):
                si_list.append(i)
            elif (vpd0 in i[0]):
                si_list.append(i)
            elif (vd1 in i[0]):
                s1_list.append(i)
            elif (vpd1 in i[0]):
                s1_list.append(i)
            elif (vd2 in i[0]):
                s2_list.append(i)
            elif (vpd2 in i[0]):
                s2_list.append(i)
            elif (vd3 in i[0]):
                s3_list.append(i)
            elif (vpd3 in i[0]):
                s3_list.append(i)
            elif (si in i[0]):
                si_list.append(i)
        for i,j in si_list:
            ds = i.split(sep='.')
            d = self.dict_info.get(ds[-1])
            si_model.appendRow([QStandardItem(str(i)),QStandardItem(d),QStandardItem(str(j))])
        self.ui.tv_system_data.setModel(si_model)
        si_model.setHorizontalHeaderLabels(header_label)
        # self.ui.tv_system_data.resizeColumnToContents(1)
        # self.ui.tv_system_data.resizeColumnToContents(2)
        
        
        for i,j in s1_list:
            ds = i.split(sep='.')
            d = self.dict_info.get(ds[-1])
            s1_model.appendRow([QStandardItem(str(i)),QStandardItem(d),QStandardItem(str(j))])
        self.ui.tv_system_data_1.setModel(s1_model)
        s1_model.setHorizontalHeaderLabels(header_label)
        # self.ui.tv_system_data_1.resizeColumnToContents(1)
        # self.ui.tv_system_data_1.resizeColumnToContents(2)

        for i,j in s2_list:
            ds = i.split(sep='.')
            d = self.dict_info.get(ds[-1])
            s2_model.appendRow([QStandardItem(str(i)),QStandardItem(d),QStandardItem(str(j))])
        self.ui.tv_system_data_2.setModel(s2_model)
        s2_model.setHorizontalHeaderLabels(header_label)
        # self.ui.tv_system_data_2.resizeColumnToContents(1)
        # self.ui.tv_system_data_2.resizeColumnToContents(2)
        if s2_list ==[] :
            self.ui.tv_system_data_2.hide()
            
        for i,j in s3_list:
            ds = i.split(sep='.')
            d = self.dict_info.get(ds[-1])
            s3_model.appendRow([QStandardItem(str(i)),QStandardItem(d),QStandardItem(str(j))])
        self.ui.tv_system_data_3.setModel(s3_model)
        s3_model.setHorizontalHeaderLabels(header_label)
        # self.ui.tv_system_data_3.resizeColumnToContents(1)
        # self.ui.tv_system_data_3.resizeColumnToContents(2)
        if s3_list ==[] :
            self.ui.tv_system_data_3.hide()

        self.ui.lb_system_name.setText(data.get(f"{self.sysid[:-1]}.StaticInfo.StationName"))
        # 'System1:200048.ValueDesc.2.SEC_NAME'
        self.ui.lb_system_s1.setText(data.get(f'{self.sysid[:-1]}.ValueDesc.1.SEC_NAME'))
        self.ui.lb_system_s2.setText(data.get(f'{self.sysid[:-1]}.ValueDesc.2.SEC_NAME'))
        self.ui.lb_system_s3.setText(data.get(f'{self.sysid[:-1]}.ValueDesc.3.SEC_NAME'))
        # self.dict_init()
    def dict_init(self):
        dict_init = dict()
        with open(file='./initfile/d.json',mode='r') as f:
            dict_init = json.load(f)
        return dict_init
            
class MySystemControl(QDialog):
    '''供热系统的控制界面'''
    def __init__(self,sysnum,user_init,index=0):
        super().__init__()
        self.ui = Ui_Form_System_Control()
        self.ui.setupUi(self)
        # print(sysnum,user_init)
        self.url = Settings.APPURL
        self.sysnum = sysnum
        self.sysnumid = sysnum[-1:]
        self.user_init = user_init
        self.data_init()
        self.ui.te_log.append(f'日志输出：数据加载完成')
        self.setWindowTitle('设备控制')
        self.ui.tabWidget.setCurrentIndex(index)
        self.thame_init()

        
        self.ctrl_thread  = Control_Thread()
        self.ctrl_thread.ctrl_signal.connect(lambda x:self.ui.te_log.append(x))

        self.ui.btn_call_real.clicked.connect(self.man_init)
        self.ui.btn_call_value.clicked.connect(self.set_value_control) 
        self.ui.btn_call_value_2.clicked.connect(self.pt_value_control)
        self.ui.btn_call_value_3.clicked.connect(self.hs_value_control)

        self.ui.btn_xhpump_bp_start_1.clicked.connect(lambda :self.xhpump_start_stop(1,5))
        self.ui.btn_xhpump_bp_stop_1.clicked.connect(lambda :self.xhpump_start_stop(1,6))
        self.ui.btn_xhpump_bp_start_2.clicked.connect(lambda :self.xhpump_start_stop(2,5))
        self.ui.btn_xhpump_bp_stop_2.clicked.connect(lambda :self.xhpump_start_stop(2,6))
        self.ui.btn_xhpump_bp_start_3.clicked.connect(lambda :self.xhpump_start_stop(3,5))
        self.ui.btn_xhpump_bp_stop_3.clicked.connect(lambda :self.xhpump_start_stop(3,6))

        self.ui.btn_call_xhpump.clicked.connect(self.set_xhpump_control)
        self.ui.btn_call_bspump.clicked.connect(self.set_bspump_control)

        self.ui.btn_bspump_bp_start_1.clicked.connect(lambda: self.bspump_start_stop(1,5))
        self.ui.btn_bspump_bp_stop_1.clicked.connect(lambda: self.bspump_start_stop(1,6))
        self.ui.btn_bspump_bp_start_2.clicked.connect(lambda: self.bspump_start_stop(2,5))
        self.ui.btn_bspump_bp_stop_2.clicked.connect(lambda: self.bspump_start_stop(2,6))

        self.ui.btn_bsvalue_man_open.clicked.connect(lambda:self.msg_bsvalue(0,1))
        self.ui.btn_bsvalue_man_close.clicked.connect(lambda:self.msg_bsvalue(0,0))
        self.ui.btn_bsvalue_auto.clicked.connect(lambda:self.msg_bsvalue(0,2))
        self.ui.btn_bsvalue_1b2_man_open.clicked.connect(lambda:self.msg_bsvalue(1,1))
        self.ui.btn_bsvalue_1b2_man_close.clicked.connect(lambda:self.msg_bsvalue(1,0))
        self.ui.btn_bsvalue_1b2_auto.clicked.connect(lambda:self.msg_bsvalue(1,2))

        self.ui.btn_bsvalue_auto_set.clicked.connect(lambda:self.msg_bsvalue(2,3))
        self.ui.btn_bsvalue_1b2_auto_set.clicked.connect(lambda:self.msg_bsvalue(3,3))

    def man_init(self):
        self.data_init()
        self.ui.te_log.append('主动更新完成!')
    def thame_init(self):
        self.stylesheet_init = open(file='themes\\dialog.qss',mode='r',encoding='utf-8').read()
        self.setStyleSheet(self.stylesheet_init)
    def data_init(self):
        res = requests.get(url=self.url+f'getone/{self.sysnum}').json()
        data:dict = res.get('data')
        station_name = data.get(f'{self.sysnum[:-1]}.StaticInfo.StationName')+"-"+data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.SEC_NAME')+'-'+data.get(f'{self.sysnum[:-1]}.update_time')
        self.ui.lb_system_name.setText(station_name)

        self.value_control(data=data)
        self.xhpump_control(data=data)
        self.bspump_control(data=data)
        self.bsvalue_control(data=data)
    def value_control(self,data:dict):
        # print(cv1_mode)
        self.ui.le_value_degree.setText(str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.CV1_U'),2)))
        self.ui.le_value_t2g.setText(str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.T2g'),2)))
        self.ui.le_value_t2j.setText(str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.SEC_AVG'),2)))
        self.ui.le_value_set_degree.setText(str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.CV1_SV'),2)))

        self.ui.le_value_pt_degree.setText(str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.CV2_U'),2)))
        self.ui.le_value_pt_set_degree.setText(str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.CV2_SV'),2)))
        self.ui.le_value_hs_degree.setText(str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.CV1h_U'),2)))
        self.ui.le_value_hs_set_degree.setText(str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.CV1h_SV'),2)))

        # t2g_time = ''
        # t2j_time = ''
        self.plctype = data.get(f'{self.sysnum[:-1]}.StaticInfo.PLCType')
        
        # for i in range(0,12):
        #     t2g_time += str(round(data.get(f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.T2g_SP_Time_{i}'),2))+','
        #     t2j_time += str(round(data.get(f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.T2gh_SP_Time_{i}'),2))+','
        #     if i ==11:
        #         t2j_time = t2j_time[:-1]
        #         t2g_time = t2g_time[:-1]
                
        self.ui.le_value_set_t2g.setText(str(round(data.get(f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.T2g_SP_Time_0'),2)))
        self.ui.le_value_set_t2j.setText(str(round(data.get(f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.T2gh_SP_Time_0'),2)))

        # self.ui.le_value_set_t2g.setText(t2g_time)
        # self.ui.le_value_set_t2j.setText(t2j_time)

        cv1_mode = data.get(f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.CV1_Mode')

        match self.plctype:
            case 'TEMP_Modbus_RNSNDJG_1'|'TEMP_Modbus_RNSNDJG_2'|'TEMP_Modbus_RNSNDJG_3':
                if cv1_mode == 1:
                    cv1_mode = 0
                elif cv1_mode ==0:
                    cv1_mode = 1
            case 'TEMP_Modbus_TFBFJG_1'|'TEMP_Modbus_TFBF1B2_1'|'TEMP_Modbus_TFABB1B2_1'|"TEMP_Modbus_TFABBJG_1"|"TEMP_Modbus_TFSNDJG_1"|"TEMP_Modbus_TFSND1B2_1":
                if cv1_mode == 2:
                    cv1_mode = 1
                elif cv1_mode ==1:
                    cv1_mode = 2



        if cv1_mode == 0:
            self.ui.rb_value_degree.setChecked(True)
        elif cv1_mode == 1:
            self.ui.rb_value_t2g.setChecked(True)
        elif cv1_mode == 2:
            self.ui.rb_value_t2j.setChecked(True)
    def xhpump_control(self,data:dict):
        xhpump_list = [
            (self.ui.lb_xhpump_here_1,('远程' if data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.XP101') else '就地')),
            (self.ui.lb_xhpump_here_2,('远程' if data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.XP201') else '就地')),
            (self.ui.lb_xhpump_here_3,('远程' if data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.XP301') else '就地')),
            (self.ui.lb_xhpump_state_1,('运行' if data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.XP102') else '停止')),
            (self.ui.lb_xhpump_state_2,('运行' if data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.XP202') else '停止')),
            (self.ui.lb_xhpump_state_3,('运行' if data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.XP302') else '停止')),
            (self.ui.lb_xhpump_good_1,('故障' if data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.XP103') else '正常')),
            (self.ui.lb_xhpump_good_2,('故障' if data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.XP203') else '正常')),
            (self.ui.lb_xhpump_good_3,('故障' if data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.XP303') else '正常')),
            (self.ui.lb_xhpump_realhz_1,str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.XP1_Hz'),2))+' Hz'),
            (self.ui.lb_xhpump_realhz_2,str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.XP2_Hz'),2))+' Hz'),
            (self.ui.lb_xhpump_realhz_3,str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.XP3_Hz'),2))+' Hz'),
            (self.ui.lb_xhpump_sethz_1,str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.XP1_SV'),2))+' Hz'),
            (self.ui.lb_xhpump_sethz_2,str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.XP2_SV'),2))+' Hz'),
            (self.ui.lb_xhpump_sethz_3,str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.XP3_SV'),2))+' Hz'),
            (self.ui.lb_xhpump_realA_1,str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.XP1_A'),2))+' A'),
            (self.ui.lb_xhpump_realA_2,str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.XP2_A'),2))+' A'),
            (self.ui.lb_xhpump_realA_3,str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.XP3_A'),2))+' A'),
            (self.ui.le_xhpump_fixhz,str(round(data.get(f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.XP_MSP'),2))),
            (self.ui.le_xhpump_difp,str(round(data.get(f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.XP_P2DSP'),2))),
            (self.ui.le_xhpump_p2g,str(round(data.get(f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.XP_P2gSP'),2))),
            
            
            
            ]
        for widget,value in xhpump_list:
            widget.setText(value)



        XP_mode = data.get(f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.XP_Mode')
        # print(self.plctype,XP_mode)
        match self.plctype:
            case 'TEMP_Modbus_TFBFJG_1'|'TEMP_Modbus_TFBF1B2_1'|'TEMP_Modbus_TFABB1B2_1'|"TEMP_Modbus_TFABBJG_1"|"TEMP_Modbus_TFSNDJG_1"|"TEMP_Modbus_TFSND1B2_1":
                if XP_mode == 2:
                    XP_mode = 1
        if XP_mode == 0:
            self.ui.rb_xhpump_fixhz.setChecked(True)
        elif XP_mode == 1:
            self.ui.rb_xhpump_difp.setChecked(True)
        elif XP_mode == 2:
            self.ui.rb_xhpump_p2g.setChecked(True)
    def bspump_control(self,data:dict):
        bhpump_list = [
            (self.ui.lb_bspump_here_1,('远程' if data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.BP101') else '就地')),
            (self.ui.lb_bspump_here_2,('远程' if data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.BP201') else '就地')),
            (self.ui.lb_bspump_state_1,('运行' if data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.BP102') else '停止')),
            (self.ui.lb_bspump_state_2,('运行' if data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.BP202') else '停止')),
            (self.ui.lb_bspump_good_1,('故障' if data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.BP103') else '正常')),
            (self.ui.lb_bspump_good_2,('故障' if data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.BP203') else '正常')),
            (self.ui.lb_bspump_realhz_1,str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.BP1_Hz'),2))+' Hz'),
            (self.ui.lb_bspump_realhz_2,str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.BP2_Hz'),2))+' Hz'),
            (self.ui.lb_bspump_sethz_1,str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.BP1_SV'),2))+' Hz'),
            (self.ui.lb_bspump_sethz_2,str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.BP2_SV'),2))+' Hz'),
            (self.ui.lb_bspump_realA_1,str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.BP1_A'),2))+' A'),
            (self.ui.lb_bspump_realA_2,str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.{self.sysnumid}.BP2_A'),2))+' A'),
            (self.ui.le_bspump_fixhz,str(round(data.get(f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.BP_MSP'),2))),
            (self.ui.le_bspump_p2h,str(round(data.get(f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.BP_P2hSP'),2))),
            # (self.ui.le_bspump_p2hhl,str(round(data.get(f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.BP_P2gSP'),2))),
            
            
            
            ]
        self.ui.le_bspump_p2hhl.setText(str(round(data.get(f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.BP_P2h_L'),2))+','+str(round(data.get(f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.BP_P2h_H'),2)))
        BP_mode = data.get(f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.BP_Mode')

        if BP_mode == 0:
            self.ui.rb_bspump_fixhz.setChecked(True)
        elif BP_mode == 1:
            self.ui.rb_bspump_p2h.setChecked(True)
        elif BP_mode == 2:
            self.ui.rb_bspump_p2hhl.setChecked(True)
        
        for widget,value in bhpump_list:
            widget.setText(value)
    def bsvalue_control(self,data:dict):
        bsvalue_list = [
            (self.ui.lb_bsvalue_water_state,('开启' if data.get(f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.SX_BSV_On') else "关闭")),
            (self.ui.lb_bsvalue_water_fun,('开启' if data.get(f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.SX_EV_Mode') else "关闭")),
            (self.ui.lb_bsvalue_water_l,str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.0.L'),2))+'m'),
            (self.ui.lb_bsvalue_water_l_start,str(round(data.get(f'{self.sysnum[:-1]}.ValueParaDesc.0.L_L_SP'),2))+'m'),
            (self.ui.lb_bsvalue_water_l_stop,str(round(data.get(f'{self.sysnum[:-1]}.ValueParaDesc.0.L_H_SP'),2))+'m'),

            (self.ui.lb_bsvalue_1b2_state,('开启' if data.get(f'{self.sysnum[:-1]}.ValueDesc.0.Flt_T_Indoor') else "关闭")),
            (self.ui.lb_bsvalue_1b2_fun,('开启' if data.get(f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.Set_Relief2_Operation_B') else "关闭")),
            (self.ui.lb_bsvalue_1b2_l,str(round(data.get(f'{self.sysnum[:-1]}.ValueDesc.0.L'),2))+'m'),
            (self.ui.lb_bsvalue_1b2_l_start,str(round(data.get(f'{self.sysnum[:-1]}.ValueParaDesc.0.Tn_L_Range'),2))+'m'),
            (self.ui.lb_bsvalue_1b2_l_stop,str(round(data.get(f'{self.sysnum[:-1]}.ValueParaDesc.0.Tn_H_Range'),2))+'m'),


            




        ]
        for widget,value in bsvalue_list:
            widget.setText(value)
        match self.plctype:
              case 'TEMP_Modbus_TFBFJG_1'|'TEMP_Modbus_TFBF1B2_1'|'TEMP_Modbus_TFABB1B2_1'|"TEMP_Modbus_TFABBJG_1"|"TEMP_Modbus_TFSNDJG_1"|"TEMP_Modbus_TFSND1B2_1":
                    self.ui.lb_bsvalue_1b2_l_start.setText(str(round(data.get(f'{self.sysnum[:-1]}.ValueParaDesc.1.1B2_SX_L_SP'),2))+'m')
                    self.ui.lb_bsvalue_1b2_l_stop.setText(str(round(data.get(f'{self.sysnum[:-1]}.ValueParaDesc.1.1B2_SX_H_SP'),2))+'m')
                    self.ui.lb_bsvalue_1b2_state.setText('开启' if data.get(f'{self.sysnum[:-1]}.ValueParaDesc.1.XSV_SS') else '关闭')
        
    def set_value_control(self):
        # CV1_MSP T2g_SP_Time_0 CV1_T2gSP T2gh_SP_Time_0
        self.ui.btn_call_value.setEnabled(False)
        self.ui.te_log.append('正在下发命令，请稍等！')
        rb_button_list = [
            (self.ui.rb_value_degree,self.ui.le_value_set_degree_2,f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.CV1_MSP'),
            (self.ui.rb_value_t2g,self.ui.le_value_set_t2g_2,f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.T2g_SP_Time_0'),
            (self.ui.rb_value_t2j,self.ui.le_value_set_t2j_2,f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.T2gh_SP_Time_0')
            ]
        cmd = {}
        data = {}
        for index,item in enumerate(rb_button_list):
            if item[0].isChecked():
                # print(item)
                if index==2:
                    self.ui.te_log.append('暂不支持该方式！！')
                    self.ui.btn_call_value.setEnabled(True)
                    return
                cmd[f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.CV1_Mode'] = index
                data['ictrlmode'] = index
                try:
                    if (item[1].text().strip() !=""):
                        tmep_f = float(item[1].text().strip())

                        val = round(tmep_f,2)
                        cmd[item[2]] = val

                except Exception as e:

                    self.ui.te_log.append(f'您输入的控制值:{item[1].text()}有误，请检查！！')
                    self.ui.te_log.append(str(e))
                    return
        data['cmd']=json.dumps(cmd)
        self.call_control(data=data,equipment=1)
        self.ui.btn_call_value.setEnabled(True)
    def set_xhpump_control(self):
        # CV1_MSP T2g_SP_Time_0 CV1_T2gSP T2gh_SP_Time_0
        self.ui.btn_call_xhpump.setEnabled(False)
        self.ui.te_log.append('正在下发命令，请稍等！')
        rb_button_list = [
            (self.ui.rb_xhpump_fixhz,self.ui.le_xhpump_set_fixhz,f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.XP_MSP'),
            (self.ui.rb_xhpump_difp,self.ui.le_xhpump_set_difp,f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.XP_P2DSP'),
            (self.ui.rb_xhpump_p2g,self.ui.le_xhpump_set_p2g,f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.T2gh_SP_Time_0')
            ]
        cmd = {}
        data = {}
        for index,item in enumerate(rb_button_list):
        # print(index,item)
            if item[0].isChecked():
                # print(item)
                if index==2:
                    self.ui.te_log.append('暂不支持该方式！！')
                    self.ui.btn_call_xhpump.setEnabled(True)
                    return
                cmd[f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.XP_Mode'] = index
                data['ictrlmode'] = 1
                try:
                    if (item[1].text().strip() !=""):
                        tmep_f = float(item[1].text().strip())
                        val = round(tmep_f,2)
                        cmd[item[2]] = val
                except Exception as e:
                    self.ui.te_log.append(f'您输入的控制值:{item[1].text()}有误，请检查！！')
                    self.ui.te_log.append(str(e))
                    return
        data['cmd']=json.dumps(cmd)
        self.call_control(data=data,equipment=2)
        self.ui.btn_call_xhpump.setEnabled(True)
    def xhpump_start_stop(self,index,cmd_index):
        # VVVF_Ctrl_0
        reply = QMessageBox()
        # reply.setStyleSheet(self.stylesheet_init)
        reply.setWindowTitle('确认命令')
        reply.setText(f'确认下发 {index}# 循环泵 {"变频启动" if cmd_index ==5 else "变频停止"} 命令？')
        btn_yes = reply.addButton("确定", QMessageBox.AcceptRole)
        btn_cancel = reply.addButton("取消", QMessageBox.RejectRole)
        btn_yes.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        btn_cancel.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        btn_yes.clicked.connect(lambda:self.start_stop_xhpump(index,cmd_index))

        res = reply.exec()
    def start_stop_xhpump(self,index,cmd_index):
        # self.sender().setEnabled(False)
        self.ui.te_log.append('正在下发命令,请稍等！')
        data = {}
        cmd = {}
        # 组织命令数据
        cmd[f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.VVVF_Ctrl_{index-1}'] = cmd_index

        data['cmd'] = json.dumps(cmd)
        data['ictrlmode'] = 0
        # print(data)

        self.call_control(data = data,equipment=2)
        # self.sender().setEnabled(True)
    def bspump_start_stop(self,index,cmd_index):
        # VVVF_Ctrl_0
        reply = QMessageBox()
        # reply.setStyleSheet(self.stylesheet_init)
        reply.setWindowTitle('确认命令')
        reply.setText(f'确认下发 {index}# 补水泵 {"变频启动" if cmd_index ==5 else "变频停止"} 命令？')
        btn_yes = reply.addButton("确定", QMessageBox.AcceptRole)
        btn_cancel = reply.addButton("取消", QMessageBox.RejectRole)
        btn_yes.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        btn_cancel.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
        btn_yes.clicked.connect(lambda:self.start_stop_bspump(index,cmd_index))
        res = reply.exec()
    def start_stop_bspump(self,index,cmd_index):
        # self.sender().setEnabled(False)
        self.ui.te_log.append('正在下发命令,请稍等！')
        data = {}
        cmd = {}
        # 组织命令数据
        cmd[f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.VVVF_Ctrl_{index+3}'] = cmd_index

        data['cmd'] = json.dumps(cmd)
        data['ictrlmode'] = 0
        print(data)

        self.call_control(data = data,equipment=3)
    # def set_xhpump_control(self):
    #     self.ui.btn_call_xhpump.setEnabled(False)
    #     self.ui.te_log.append('正在下发命令,请稍等！')
    #     rb_button_list = [
    #         (self.ui.rb_xhpump_fixhz,self.ui.le_xhpump_set_fixhz,f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.XP_MSP'),
    #         (self.ui.rb_xhpump_difp,self.ui.le_xhpump_set_difp,f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.XP_P2DSP'),
    #         (self.ui.rb_xhpump_p2g,self.ui.le_xhpump_set_p2g,f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.XP_P2gSP')

    #     ]

    #     cmd = {}
    #     data = {}
    #     for index,item in enumerate(rb_button_list):
    #         if item[0].isChecked():
    #             cmd[f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.XP_Mode'] = index
    #             data['ictrlmode']= 0
    #             try:
    #                 if (item[1].text().strip() !=""):
    #                     tmep_f = float(item[1].text().strip())

    #                     val = round(tmep_f,2)
    #                     cmd[item[2]] = val

    #             except Exception as e:
    #                 self.ui.te_log.append(f'您输入的控制值:{item[1].text()}有误，请检查！！')
    #                 self.ui.te_log.append(str(e))
    #                 self.ui.btn_call_xhpump.setEnabled(True)

    #                 return
    #     data['cmd'] = json.dumps(cmd)
    #     self.call_control(data = data,equipment=2)
    #     self.ui.btn_call_xhpump.setEnabled(True)
    def set_bspump_control(self):
        self.ui.btn_call_bspump.setEnabled(False)
        self.ui.te_log.append('正在下发命令,请稍等！')
        rb_button_list = [
            (self.ui.rb_bspump_fixhz,self.ui.le_bspump_set_fixhz,f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.BP_MSP'),
            (self.ui.rb_bspump_p2h,self.ui.le_bspump_set_p2h,f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.BP_P2hSP'),
            (self.ui.rb_bspump_p2hhl,self.ui.le_bspump_set_p2hhl,f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.BP_P2h_L')
            # (self.ui.rb_bspump_p2hhl,self.ui.le_bspump_set_p2hhl_2,f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.BP_P2h_H')

        ]

        cmd = {}
        data = {}
        for index,item in enumerate(rb_button_list):
            if item[0].isChecked():
                cmd[f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.BP_Mode'] = index
                data['ictrlmode']= 1
                if index == 2:
                    try:
                        if(item[1].text().strip()!="") and (self.ui.le_bspump_set_p2hhl_2.text().strip()!=""):
                            temp_l = float(item[1].text().strip())
                            temp_h = float(self.ui.le_bspump_set_p2hhl_2.text().strip())
                            val_l = round(temp_l,2)
                            val_h = round(temp_h,2)
                            cmd[item[2]] = val_l
                            cmd[f'{self.sysnum[:-1]}.ValueParaDesc.{self.sysnumid}.BP_P2h_H'] = val_h
                    except Exception as e:
                        self.ui.te_log.append(f'您输入的控制值:{item[1].text()}有误，请检查！！')
                        self.ui.te_log.append(str(e))
                        self.ui.btn_call_xhpump.setEnabled(True)
                        return
                try:
                    if (item[1].text().strip() !=""):
                        tmep_f = float(item[1].text().strip())

                        val = round(tmep_f,2)
                        cmd[item[2]] = val

                except Exception as e:
                    self.ui.te_log.append(f'您输入的控制值:{item[1].text()}有误，请检查！！')
                    self.ui.te_log.append(str(e))
                    self.ui.btn_call_xhpump.setEnabled(True)
                    return
        data['cmd'] = json.dumps(cmd)
        self.call_control(data = data,equipment=3)
        self.ui.btn_call_bspump.setEnabled(True)
    def call_control(self,data:dict,equipment:int):
        # equipment:1 value 2 xhpump 3 bspump 4 bsvalue 5ptvalue 6hsvalue
        username = self.user_init.get('username')
        hostname = socket.gethostname()
        data['username'] = username
        data['hostname'] = hostname
        data['equipment'] = equipment
        data['pvsssysno'] = self.sysnum[6:7]
        data['vpnuserid'] = self.sysnum[-7:-1]
        data['unitnumberid'] = self.sysnumid
        # print(data)
        # print(json.dumps(data))
        self.ctrl_thread.set_data(data=data)
        self.ctrl_thread.start()
    def msg_bsvalue(self,index,cmd_index):
                # VVVF_Ctrl_0
        if index in [0,1]:
            cmd_index_list = ('手动关闭','手动开启','自动模式')
            index_index_list = ('自来水水箱电磁阀','一补二水箱电磁阀')
            
            reply = QMessageBox()
            reply.setWindowTitle('确认命令')
            reply.setText(f'确认下发 {index_index_list[index]}  {cmd_index_list[cmd_index]} 命令？')
            btn_yes = reply.addButton("确定", QMessageBox.AcceptRole)
            btn_cancel = reply.addButton("取消", QMessageBox.RejectRole)
            btn_yes.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
            btn_cancel.setCursor(QCursor(Qt.CursorShape.PointingHandCursor))
            btn_yes.clicked.connect(lambda:self.set_bsvalue_control(index,cmd_index))
            res = reply.exec()
        else:
            self.set_bsvalue_control(index,cmd_index)

        
    def set_bsvalue_control(self,index,cmd_index):
        self.ui.te_log.append('正在下发命令,请稍等!')
        data = {}
        cmd = {}
        match index:
            case 0:
                cmd[f'{self.sysnum[:-1]}.ValueParaDesc.0.SX_EV_Mode'] = cmd_index
            case 1:
                cmd[f'{self.sysnum[:-1]}.ValueParaDesc.1.Set_Relief2_Operation_B'] = cmd_index
            case 2: 
                try:
                    if (self.ui.le_bsvalue_water_l.text().strip() and self.ui.le_bsvalue_water_h.text().strip()):
                        tmep_l = float(self.ui.le_bsvalue_water_l.text().strip())
                        tmep_h = float(self.ui.le_bsvalue_water_h.text().strip())

                        val_l = round(tmep_l,2)
                        val_h = round(tmep_h,2)
                        cmd[f'{self.sysnum[:-1]}.ValueParaDesc.0.L_L_SP'] = val_l
                        cmd[f'{self.sysnum[:-1]}.ValueParaDesc.0.L_H_SP'] = val_h

                    else :
                        self.ui.te_log.append("空值无效！")
                        return
                except Exception as e:

                    self.ui.te_log.append(f'您输入的控制值:{self.ui.le_bsvalue_water_l.text()}  {self.ui.le_bsvalue_water_h.text()}有误，请检查！！')
                    self.ui.te_log.append(str(e))
                    return
            case 3:
                try:
                    if (self.ui.le_bsvalue_1b2_l.text().strip() and self.ui.le_bsvalue_1b2_h.text().strip()):
                        tmep_l = float(self.ui.le_bsvalue_1b2_l.text().strip())
                        tmep_h = float(self.ui.le_bsvalue_1b2_h.text().strip())

                        val_l = round(tmep_l,2)
                        val_h = round(tmep_h,2)
                        cmd[f'{self.sysnum[:-1]}.ValueParaDesc.0.Tn_L_Range'] = val_l
                        cmd[f'{self.sysnum[:-1]}.ValueParaDesc.0.Tn_H_Range'] = val_h

                    else :
                        self.ui.te_log.append("空值无效！")
                        return
                except Exception as e:

                    self.ui.te_log.append(f'您输入的控制值:{self.ui.le_bsvalue_1b2_l.text()}  {self.ui.le_bsvalue_1b2_h.text()}有误，请检查！！')
                    self.ui.te_log.append(str(e))
                    return

        data['cmd'] = json.dumps(cmd)
        data['ictrlmode'] = 0
        self.call_control(data=data,equipment=4)
        # print('bsvalue's)
    def pt_value_control(self):
        self.ui.te_log.append('正在下发命令,请稍等!')
        data = {}
        cmd = {}
        try:
            if (self.ui.le_value_pt_set_degree_2.text().strip()):
                tmep_f = float(self.ui.le_value_pt_set_degree_2.text().strip())

                val = round(tmep_f,2)
                cmd[f'{self.sysnum[:-1]}.ValueParaDesc.1.CV2_MSP'] = val
            else :
                self.ui.te_log.append("空值无效！")
                return
        except Exception as e:

            self.ui.te_log.append(f'您输入的控制值:{self.ui.le_value_pt_set_degree_2.text()}有误，请检查！！')
            self.ui.te_log.append(str(e))
            return

        data['cmd'] = json.dumps(cmd)
        data['ictrlmode'] = 0
        self.call_control(data=data,equipment=5)
    def hs_value_control(self):
        self.ui.te_log.append('正在下发命令,请稍等!')
        data = {}
        cmd = {}
        try:
            if (self.ui.le_value_hs_set_degree_2.text().strip()):
                tmep_f = float(self.ui.le_value_hs_set_degree_2.text().strip())

                val = round(tmep_f,2)
                cmd[f'{self.sysnum[:-1]}.ValueParaDesc.1.CV1h_MSP'] = val
            else :
                self.ui.te_log.append("空值无效！")
                return
        except Exception as e:

            self.ui.te_log.append(f'您输入的控制值:{self.ui.le_value_hs_set_degree_2.text()}有误，请检查！！')
            self.ui.te_log.append(str(e))
            return


        data['cmd'] = json.dumps(cmd)
        data['ictrlmode'] = 0
        self.call_control(data=data,equipment=6)
        # pass
        # System2:100001.ValueParaDesc.1.CV2_MSP
        # System2:100001.ValueParaDesc.1.CV2_MSP 旁通
        # System2:100001.ValueParaDesc.1.CV1h_MSP 回水
class Control_Thread(QThread):
    ctrl_signal = Signal(str)
    def __init__(self):
        super().__init__()

    def run(self):
        res = requests.post(url=Settings.APPURL+'/api117/control',data=json.dumps(self.data).encode('utf-8'))
        log = res.json().get('log')
        self.ctrl_signal.emit(log)


    def set_data(self,data:dict):
        print(data)
        self.data = data
    


